﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;
using System.IO;

namespace Web.Product
{
    public partial class EditProduct : System.Web.UI.Page
    {
        static long? assignedToID = null;
        static string prevPage = String.Empty;
        static PRODUCT proDe;
        // need PRODUCT_ID
        static long ProID;
        static USER user;
        static string defaultImage = "~/ProductImages/no_image_for_this_product.gif";
        static bool clickdelete = false;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            if (Request.UrlReferrer != null)
            {
                prevPage = Request.UrlReferrer.ToString();
                hdntxtPrevPage.Value = prevPage;
            }
            assignedToID = null;
            user = (USER)Session["User"];
            if (user != null)
            {
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    assignedToID = user.ID;
                    divAssignedTo.Visible = false;
                }
                string requestEdit = Request.QueryString["id"];
                if (requestEdit != null)
                {
                    ProID = Convert.ToInt64(requestEdit);
                    LoadAllUser();
                    LoadSupplier();
                    LoadUsageUnit();

                    LoadDataProductEdit();
                    clickdelete = false;
                }
            }
        }
        private void LoadDataProductEdit()
        {

            proDe = ProductService.GetProductByID(ProID);
            if (proDe != null)
            {
                //Product Details
                txtProductName.Text = proDe.PRODUCT_NAME;
                if (proDe.PRODUCT_ACTIVE == true)
                    chbProductActive.Checked = true;
                else chbProductActive.Checked = false;
                txtSerialNo.Text = proDe.SERIAL_NO;
                dpSalesStartDate.SelectedDate = proDe.SALES_START_DATE;
                if (proDe.MANUFACTURER_ID != null)
                    ddlSupplier.FindItemByValue(proDe.MANUFACTURER_ID.ToString()).Selected = true;
                txtProductCategory.Text = proDe.PRODUCT_CATEGORY;
                dpSupportStartDate.SelectedDate = proDe.SUPPORT_START_DATE;
                dpSalesEndDate.SelectedDate = proDe.SALES_END_DATE;
                dpSupportExpiryDate.SelectedDate = proDe.SUPPORT_EXPIRY_DATE;
                txtWebsite.Text = proDe.WEBSITE;
                //Pricing Information
                rntxtUnitprice.Value = proDe.UNIT_PRICE;
                rntxtCommissionRate.Value = proDe.COMMISSION_RATE;
                if (proDe.GST_PERCENT != null)
                {
                    panelGST.Style.Add("display", "block");
                    chbGST.Checked = true;
                }
                if (proDe.SALES_PERCENT != null)
                {
                    panelSales.Style.Add("display", "block");
                    chbSales.Checked = true;
                }
                if (proDe.SERVICE_PERCENT != null)
                {
                    panelService.Style.Add("display", "block");
                    chbService.Checked = true;
                }
                if (proDe.ASSIGN_TO != null)
                    ddlAssignedTo.FindItemByValue(proDe.ASSIGN_TO.ToString()).Selected = true;
                //Stock Information
                if (proDe.USAGE_UNIT_ID != null)
                    ddlUsageUnit.FindItemByValue(proDe.USAGE_UNIT_ID.ToString()).Selected = true;
                rntxtQuantity.Value = proDe.BALANCE;
                rntxtReorderLevel.Value = proDe.REORDER_LEVEL;
                rntxtQtyInDemand.Value = proDe.QTY_IN_DEMAND;
                //Description Detail
                txtDescription.Text = proDe.DESCRIPTION;

                // Product Image Information
                imgprw.Src = proDe.IMAGE;
            }
            else
            {
                divContent.Style["display"] = "none";
                divError.Style["display"] = "block";
            }
        }
        private void LoadAllUser()
        {
            ddlAssignedTo.Items.Clear();
            List<USER> users = UserService.ListAll();
            if (users != null)
            {
                foreach (USER u in users)
                {
                    ddlAssignedTo.Items.Add(new RadComboBoxItem(u.SUR_NAME + " " + u.NAME, u.ID.ToString()));
                }
            }
        }
        private void LoadUsageUnit()
        {
            ddlUsageUnit.DataSource = ProductService.GetProductUsageUnit();
            ddlUsageUnit.DataBind();
        }
        private void LoadSupplier()
        {
            ddlSupplier.DataSource = ProductService.GetProductManufacturer();
            ddlSupplier.DataBind();
        }

        private int updateProduct()
        {
            //General information
            DateTime dt = DateTime.Now;
            proDe.DATE_ENTERED = dt;
            proDe.DATE_MODIFIED = dt;
            //Product detail
            proDe.PRODUCT_NAME = txtProductName.Text.Trim();
            proDe.PRODUCT_ACTIVE = chbProductActive.Checked;
            proDe.SERIAL_NO = txtSerialNo.Text.Trim();
            proDe.SALES_START_DATE = dpSalesStartDate.SelectedDate;
            if (ddlSupplier.SelectedValue != "-1")
                proDe.MANUFACTURER_ID = Convert.ToInt64(ddlSupplier.SelectedValue);
            proDe.PRODUCT_CATEGORY = txtProductCategory.Text.Trim();
            proDe.SUPPORT_START_DATE = dpSupportStartDate.SelectedDate;
            proDe.SALES_END_DATE = dpSalesEndDate.SelectedDate;
            proDe.SUPPORT_EXPIRY_DATE = dpSupportExpiryDate.SelectedDate;
            //proDe.VENDOR_ID = 1;//fix later
            proDe.WEBSITE = txtWebsite.Text.Trim();
            //Pricing Information
            proDe.UNIT_PRICE = rntxtUnitprice.Value;
            proDe.COMMISSION_RATE = rntxtCommissionRate.Value;
            if (chbGST.Checked)
                proDe.GST_PERCENT = rntxtGST.Value;
            if (chbSales.Checked)
                proDe.SALES_PERCENT = rntxtSales.Value;
            if (chbService.Checked)
                proDe.SERVICE_PERCENT = rntxtService.Value;

            //Stock Information
            if (ddlUsageUnit.SelectedValue != "-1")
                proDe.USAGE_UNIT_ID = Convert.ToInt64(ddlUsageUnit.SelectedValue);
            double? oldinstock = proDe.QTY_IN_STOCK;
            double? oldquantity = proDe.BALANCE;
            proDe.QTY_IN_STOCK = oldinstock + rntxtQuantity.Value - oldquantity ;
            proDe.BALANCE = rntxtQuantity.Value;
            proDe.REORDER_LEVEL = rntxtReorderLevel.Value;

            if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                proDe.ASSIGN_TO = user.ID;
            else
            {
                if (ddlAssignedTo.SelectedItem == null)
                    proDe.ASSIGN_TO = null;
                else
                    proDe.ASSIGN_TO = Convert.ToInt64(ddlAssignedTo.SelectedValue);
            }

            proDe.QTY_IN_DEMAND = rntxtQtyInDemand.Value;
            //Description detail
            proDe.DESCRIPTION = txtDescription.Text.Trim();
            //Product image
            string img = proDe.IMAGE;
            //if (FileUploadControl.HasFile)
            if (AsyncUpload1.UploadedFiles.Count > 0)
            {
                AsyncUpload1.UploadedFiles[0].SaveAs("~/ProductImages/" + DateTime.Now.ToString("ddMMyyhhmmssttfff") + AsyncUpload1.UploadedFiles[0].GetExtension());
                if (img != defaultImage)
                    System.IO.File.Delete(Server.MapPath(proDe.IMAGE));
                string filename = "~/ProductImages/" + DateTime.Now.ToString("ddMMyyhhmmssttfff") + AsyncUpload1.UploadedFiles[0].GetExtension();
                AsyncUpload1.UploadedFiles[0].SaveAs(Server.MapPath(filename));
                proDe.IMAGE = filename;
            }
            else
            {
                if ((clickdelete == true) && (img != defaultImage))
                {
                    System.IO.File.Delete(Server.MapPath(proDe.IMAGE));
                    proDe.IMAGE = defaultImage;
                }
            }

            return ProductService.UpdateProduct(proDe);
        }

        protected void btn_Delete_ServerClick(object sender, EventArgs e)
        {
            int ProDel = ProductService.DeleteProduct(ProID);
            if (ProDel == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Delete product successful !" + "','" + "Products.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Delete product successful !", "Products.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete product !" + "');");
            //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not delete product !');", true);
        }
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            int newProductResult = updateProduct();
            if (newProductResult == 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Update product successful !" + "','" + "Products.aspx" + "');");
                //MessageBox.Show(this.Page, Page.GetType(), "Update product successful !", "Products.aspx");
            }
            else
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not update product !" + "');");
            //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not update product !');", true);
        }
        protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
        {
            //Bind the RadComboBod 
            LoadSupplier();
            ddlSupplier.FindItemByValue(proDe.MANUFACTURER_ID.ToString()).Selected = true;
        }

        protected void DeleteImage_Click(object sender, EventArgs e)
        {
            imgprw.Src = defaultImage;
            clickdelete = true;
        }
    }
}